<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
        // ID of logged in user.
        private $_id;
	/**
	 * Authenticate a user.
         * 
         * DB-authentication and encryption method based on:
         * http://www.yiiframework.com/wiki/283/secure-password-hash-storage-and-a-yii-helper-extension/
	 * 
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
            
            // Search for user by username
            $user = User::model()->findByAttributes(array(
                'username' => $this->username,
            ));
            
            if(is_null($user) ||
                    crypt($this->password, $user->password) !== $user->password
            ){
                // Don't specify which attribute is wrong, username or password.
                $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
            }else
            {
                $this->_id = $user->user_ID;
                $this->errorCode=self::ERROR_NONE;
            }
            
            return !$this->errorCode;
	}
        
        /**
         * Get the user_ID of the logged in user.
         * 
         * @return int
         */
        public function getId()
        {
                return $this->_id;
        }
}